package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.OrderDataDistributeInfo;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.github.pagehelper.PageHelper;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.model.Refund;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.dto.mqdto.SmsDto;
import com.ytjj.common.enums.PaySourceEnum;
import com.ytjj.common.enums.PlatformEnum;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.YxAlipayConfig;
import com.ytjj.common.model.request.AliyunMallRequest;
import com.ytjj.common.service.AlipayService;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.*;
import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.common.constants.PlatformConstant;
import com.ytjj.qmyx.admin.dao.*;
import com.ytjj.qmyx.admin.mapper.OrderDisparitiesRefundMapper;
import com.ytjj.qmyx.admin.mapper.OrdersForbidMapper;
import com.ytjj.qmyx.admin.model.Admin;
import com.ytjj.qmyx.admin.model.OrderDisparitiesRefund;
import com.ytjj.qmyx.admin.model.OrdersForbid;
import com.ytjj.qmyx.admin.model.RegisterInsertRequest;
import com.ytjj.qmyx.admin.model.request.ReturnRegisterRequest;
import com.ytjj.qmyx.admin.model.request.UpdateOrderStatusRequest;
import com.ytjj.qmyx.admin.model.request.UsersBalanceRecordRequest;
import com.ytjj.qmyx.admin.model.response.OrderQueryResponse;
import com.ytjj.qmyx.admin.model.response.OrdersForbidResponse;
import com.ytjj.qmyx.admin.model.response.ReturnRegisterResponse;
import com.ytjj.qmyx.admin.service.*;
import com.ytjj.qmyx.admin.service.adapay.AdaPayService;
import com.ytjj.qmyx.admin.service.channelProductService.ChannelProductService;
import com.ytjj.qmyx.admin.utils.UserUtil;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.qmyx.users.mapper.UsersMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.LinkedMap;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 *
 * @Version: 1.0
 */
@Service
@Slf4j
public class ReturnRegisterServiceImpl implements ReturnRegisterService {

    @Resource
    private ReturnRegisterDao returnRegisterDao;
    @Resource
    private ReturnRegisterMapper returnRegisterMapper;
    @Autowired
    private MemberService memberService;
    @Autowired
    private OrderNoteDao orderNoteDao;
    @Resource
    private ReturnRegisterNoteDao returnRegisterNoteDao;
    @Resource
    private OrdersDao ordersDao;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;
    @Resource
    private OrdersRefundMapper refundMapper;
    @Resource
    private AlipayService alipayService;
    @Resource
    private ReturnGoodsDao returnGoodsDao;
    @Resource
    private SupplyApiConfig supplyApiConfig;
    @Resource
    private MallClient mallClient;
    @Resource
    private UsersBalanceRecordService usersBalanceRecordService;
    @Autowired
    @Lazy
    private ReturnGoodsService returnGoodsService;
    @Autowired
    private AdaPayService adaPayService;
    @Resource
    private OrdersPayMapper ordersPayMapper;
    @Autowired
    @Lazy
    private ReturnRegisterService thisProxy;
    @Autowired
    private UsersClient usersClient;
    @Resource
    private ChannelProductService channelProductService;
    @Resource
    private OrdersForbidMapper ordersForbidMapper;
    @Resource
    private PayConfigMapper payConfigMapper;
    @Value("${wxRefundText:余额不足}")
    private String wxRefundText;
    @Value("${aliPayRefundText:余额不足}")
    private String aliPayRefundText;
    @Resource
    private WxComplaintsService complaintsService;
    @Resource
    private AliPayComplaintsService aliPayComplaintsService;
    @Resource(name = "guchuangRabbitTemplate")
    private RabbitTemplate guchuangRabbitTemplate;

//    @Resource(name = "jumaiduoRabbitTemplate")
//    private RabbitTemplate jumaiduoRabbitTemplate;
//
//    @Resource(name = "yiquanRabbitTemplate")
//    private RabbitTemplate yiquanRabbitTemplate;
//
//    @Resource(name = "zxlpRabbitTemplate")
//    private RabbitTemplate zxlpRabbitTemplate;
//
//    @Resource(name = "ygyxRabbitTemplate")
//    private RabbitTemplate ygyxRabbitTemplate;
//
//    @Resource(name = "yxhdRabbitTemplate")
//    private RabbitTemplate yxhdRabbitTemplate;
//
//    @Resource(name = "jckjRabbitTemplate")
//    private RabbitTemplate jckjRabbitTemplate;

    //您购买的（商品名儿童手表）订单退款申请成功，款项（退款额29元）已原路退回到微信/支付宝，敬请留意查收！后续如有疑问或问题您可以在商城上班时间段（9：00-12：00，13：45-18：30）拨打客服热线0000001727或点（链接）咨询人工客服，我们一定会竭诚为您服务！
    @Value("${refundMessage:您购买的（商品名:%s）订单退款申请成功，款项（退款额:%s元）已原路退回到%s，敬请留意查收！后续如有疑问或问题您可以在商城上班时间段（9：00-12：00，13：45-18：30）拨打客服热线0000001727或点（uqt3.cn/rQ9CZ）咨询人工客服，我们一定会竭诚为您服务！}")
    private String refundMessage;

    @Resource
    private RedisService redisService;

    @Value("${quanmingyanxuan.adapay.REFUND_NOTIFY_URL}")
    private String REFUND_NOTIFY_URL;



    @Override
    public Integer insertReturnRegister(RegisterInsertRequest request) {
        Admin admin = memberService.getAdmin();

        ReturnRegister returnRegister = new ReturnRegister();

        BeanUtils.copyProperties(request, returnRegister);

        returnRegister.setOperationName(admin.getName());
        returnRegister.setOperationTime(new Date());

        //同步订单小记
        OrderNote orderNote = new OrderNote();
        orderNote.setOrderInfoId(returnRegister.getOrderInfoId());
        orderNote.setContent(admin.getName()+"增加原路登记！");
        orderNote.setAdminId(admin.getId());
        orderNote.setCreateTime(new Date());
        orderNoteDao.insertOrderNote(orderNote);

        returnRegister.setStatus(0);

        //获取原订单号
        String oldTradeNo = ordersDao.getExpressNo(returnRegister.getOrderInfoId());
        returnRegister.setOldTradeNo(oldTradeNo);
        returnRegister.setRealTotalMoney(request.getRealTotalMoney());
        return returnRegisterDao.insertReturnRegister(returnRegister);
    }


    @Override
    public CommonPage<ReturnRegisterResponse> selectList(ReturnRegisterRequest returnRegisterRequest) {
        PageHelper.startPage(returnRegisterRequest.getPageNum(), returnRegisterRequest.getPageSize());
        List<ReturnRegisterResponse> pageList = returnRegisterDao.selectList(returnRegisterRequest);
        if (!CollectionUtils.isEmpty(pageList)) {
            List<Integer> bankerIds = pageList.stream().map(ReturnRegisterResponse::getBankerId).collect(Collectors.toList());
            BankerRequest bankerRequest = new BankerRequest();
            bankerRequest.setBankerIdList(bankerIds);
            String json = JSON.toJSONString(bankerRequest);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getBankerMsg", json, supplyApiConfig.getHeadsMap());
            List<BankerResponse> bankerResponses = JSONObject.parseArray(result, BankerResponse.class);
            log.info("================bankerResponses:{}======",result);

            List<Integer> productIdList = pageList.stream().filter(item -> null != item.getProductId()).map(ReturnRegisterResponse::getProductId).collect(Collectors.toList());
            ProductExample example = new ProductExample();
            example.createCriteria().andIdIn(productIdList);
            List<Product> products = productMapper.selectByExample(example);


            List<String> childOrderNoList = pageList.stream().map(ReturnRegisterResponse::getChildOrderNo).collect(Collectors.toList());
            List<OrderQueryResponse> orderQueryResponses = returnGoodsService.querySupplyChainOrderInfo(childOrderNoList);

            List<Integer> orderInfoIdList = pageList.stream().map(ReturnRegisterResponse::getOrderInfoId).collect(Collectors.toList());
            List<Integer> lockOrderInfoIdList = returnGoodsDao.getLockOrderInfo(orderInfoIdList);

            boolean isLimitRole = channelProductService.checkIsLimitRole();
            boolean checkUserPhoneFlag = returnGoodsService.checkUserPhoneIsLimitRole();
            for (ReturnRegisterResponse rrr : pageList) {
                String notes = "";
                List<ReturnRegisterNote> list = returnRegisterNoteDao.getNotes(rrr.getId());
                if (!CollectionUtils.isEmpty(list)) {
                    for (ReturnRegisterNote note : list) {
                        notes += " // " + note.getContent();
                    }
                }
                rrr.setNotes(notes);

                //供应商成本
                Optional<OrderQueryResponse> first = orderQueryResponses.stream().filter(item -> item.getChildOrderNo().equals(rrr.getChildOrderNo())).findFirst();
                rrr.setCostPrice(first.map(OrderQueryResponse::getCostPrice).orElse(null));

                //图片视频转换List
                if("img".equals(rrr.getFileType()) && rrr.getFile() != null) {
                    String imgUrl = rrr.getFile();
                    String[] imgArray = imgUrl.split(",");
                    List<Map<String, String>> imgList = new ArrayList<>();
                    for(String img : imgArray) {
                        Map<String, String> map = new HashMap<>();
                        map.put("img", img);
                        imgList.add(map);
                    }
                    rrr.setFileList(imgList);
                }
                //招商员
                List<BankerResponse> bankers = bankerResponses.stream().filter(item -> item.getBankerId().equals(rrr.getBankerId())).collect(Collectors.toList());
                log.info("===========================bankers:{}==========",bankers);
                if (!CollectionUtils.isEmpty(bankers)){
                    BankerResponse bankerResponse = bankers.get(0);
                    if (null != bankerResponse) {
                        rrr.setBuyer(bankerResponse.getBuyer());
                        rrr.setWarehouseName(isLimitRole ? "******" : bankerResponse.getBankerName());
                    }
                }
                //支付方式
                OrdersPay ordersPay =  ordersDao.queryOrdersPayByResOrderNo(rrr.getTradeNo());
                String payName = PaySourceEnum.getPayType(ordersPay.getTradeType());
                rrr.setPaySource(payName);

                if (!com.alibaba.excel.util.CollectionUtils.isEmpty(products)) {
                    List<Product> collect1 = products.stream().filter(item -> item.getId().equals(rrr.getProductId())).collect(Collectors.toList());
                    rrr.setSupplyProductId(com.alibaba.excel.util.CollectionUtils.isEmpty(collect1) ? 0 : collect1.get(0).getSupplyProductId());
                }
                //是否锁单
                if (CollectionUtils.isEmpty(lockOrderInfoIdList)) {
                    List<Integer> collect = lockOrderInfoIdList.stream().filter(item -> item.equals(rrr.getOrderInfoId())).collect(Collectors.toList());
                    rrr.setLockFlag(CollectionUtils.isEmpty(collect) ? 2 :1);
                } else {
                    rrr.setLockFlag(2);
                }
                //手机号脱敏
                if (org.apache.commons.lang3.StringUtils.isNotBlank(rrr.getUserPhone())){
                    rrr.setUserPhone(checkUserPhoneFlag ? rrr.getUserPhone() : rrr.getUserPhone().replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2"));
                }

            }
        }

        return CommonPage.restPage(pageList);
    }

    @Override
    public Integer updateReturnRegister(ReturnRegisterRequest returnRegisterRequest) {
        return returnRegisterDao.updateReturnRegister(returnRegisterRequest);
    }

    @Override
    public Integer delReturnRegister(Integer id) {
        //移除时增加小记
        Admin admin = memberService.getAdmin();
        ReturnRegisterNote note = new ReturnRegisterNote();
        note.setReturnRegisterId(id);
        note.setContent(admin.getName()+"移除了该订单！");
        note.setAdminName(admin.getName());
        note.setCreateTime(new Date());
        returnRegisterNoteDao.insertNote(note);
        return returnRegisterDao.delReturnRegister(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult refund(Integer id, String refundDesc, ReturnRegister register, OrdersInfo ordersInfo) {
        OrdersForbid ordersForbid = new OrdersForbid();
        ordersForbid.setOrdersInfoId(ordersInfo.getId());
        ordersForbid.setForbidType(2);
        //是否禁止退款
        OrdersForbidResponse lockOrderInfo = ordersForbidMapper.getLockOrderInfo(ordersForbid);
        if(lockOrderInfo != null && lockOrderInfo.getStatus() == 0){
            throw new ApiException("该订单已被禁止退款！请解除后再试！");
        }
        if (StringUtils.isEmpty(refundDesc)){
            //默认:平台退款
            refundDesc = "平台退款";
        }
        // 3.查询订单
         Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());
        // 4.查询退货单
        ReturnGoods returnGoods = returnGoodsDao.selectReturnGoodsByWaitBackAmount(ordersInfo.getId());

        if (null == returnGoods || null == returnGoods.getId()) {
            throw new ApiException("退款申请审核未通过，不能发起退款！");
        }

//        if (2 != returnGoods.getAfterType() && 4 != returnGoods.getStatus()){
//            throw new ApiException("该售后单未完成售后流程,不能退款");
//        }

        // 验证
        if (orders.getIsPay().byteValue() == (byte) 0) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ORDER_NOT_REFUND));
        }
        if (ordersInfo.getIsRefund().intValue() == 1) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.NOT_START_REFUND));
        }
        // 获取该订单下的支付信息
        OrdersPay ordersPay = ordersDao.queryOrdersPayByResOrderNo(orders.getTradeNo());


        OrdersRefundExample example = new OrdersRefundExample();
        example.createCriteria().andOrdersInfoIdEqualTo(register.getOrderInfoId());
        List<OrdersRefund> refundList = refundMapper.selectByExample(example);
        OrdersRefund ordersRefund;
        if (refundList != null && refundList.size() > 0 && !"UPAY".equals(ordersPay.getTradeType()) && !"HFTX".equals(ordersPay.getTradeType()) && !"ZSY".equals(ordersPay.getTradeType())  && !"MHKJ".equals(ordersPay.getTradeType())) {
            ordersRefund = refundList.get(0);
            if (ordersRefund.getStatus().intValue() == 1) {
                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.APPLICATION_FOR_DRAWBACK));
            }
            if (ordersRefund.getStatus().intValue() == 2) {
                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.NOT_START_REFUND));
            }
        } else {
            //判断现金该退多少钱
            int amount = returnGoods.getAmount().multiply(new BigDecimal(100)).intValue();//申请退款的金额
            Integer realTotalTotalFee = orders.getRealTotalMoney().multiply(new BigDecimal(100)).intValue();//实际支付金额
            Integer realTotalMoneyRefund = 0;
            if (null != orders.getRealTotalMoneyRefund()){
                realTotalMoneyRefund = orders.getRealTotalMoneyRefund().multiply(new BigDecimal(100)).intValue();//已退部分后还剩的实付金额
            }
            Integer refundFee = realTotalTotalFee;
            if (null != orders.getDeductionMoney() && orders.getDeductionMoney().compareTo(new BigDecimal(0)) > 0){
                if (null == orders.getRealTotalMoneyRefund()){
                    if (amount <= realTotalTotalFee){
                        refundFee = amount;
                    }
                }else {
                    if (amount <= realTotalMoneyRefund){
                        refundFee = amount;
                    }else {
                        refundFee = realTotalMoneyRefund;
                    }
                }
            }else {
                //没用余额的,给退多少是多少
                refundFee = amount;
            }
            ordersRefund = new OrdersRefund();
            ordersRefund.setOrderNo(orders.getOrderNo());
            ordersRefund.setOrdersInfoId(ordersInfo.getId());
            ordersRefund.setTradeNo(orders.getTradeNo());
            ordersRefund.setRefundNo(OrderUtils.getRefundCode(orders.getId()));
            ordersRefund.setTotalFee(realTotalTotalFee);
            ordersRefund.setRefundFee(refundFee);//-----------------------------------退款金额
            ordersRefund.setRefundDesc(refundDesc);
            ordersRefund.setCreateTime(new Date());
            ordersRefund.setStatus(1);
            refundMapper.insertSelective(ordersRefund);
        }



        //如果没有支付信息(纯余额支付),退回用户余额
        if (null == ordersPay ||
                (null != orders.getRealTotalMoneyRefund() && orders.getRealTotalMoneyRefund().compareTo(new BigDecimal(0)) == 0) ||
                    orders.getRealTotalMoney().compareTo(new BigDecimal(0)) == 0){
            returnBalance(register, ordersInfo, orders, returnGoods, ordersRefund);
            if (null != returnGoods.getAfterType() && returnGoods.getAfterType() == 1){
                //售后类型为退款 把库存加回来
                try {
                    Product product = productMapper.selectByPrimaryKey(ordersInfo.getProductId());
                    subAndAddStock(ordersInfo.getChildOrderNo(),ordersInfo.getProductSum(),product.getIsZeroProduct(),"add");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return CommonResult.success();
        } else {
            //调用支付接口退款
            CommonResult commonResult = handleRefundV4(orders, ordersRefund, ordersInfo, ordersPay, register, returnGoods, refundDesc);
            return commonResult;
        }
    }



    /**
     * 处理退款接口
     * @param orders
     * @param ordersRefund
     * @param ordersInfo
     * @param ordersPay
     * @param register
     * @param returnGoods
     * @param refundDesc
     * @return void
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResult handleRefundV4(Orders orders,OrdersRefund ordersRefund,OrdersInfo ordersInfo,OrdersPay ordersPay,ReturnRegister register,ReturnGoods returnGoods,String refundDesc){
        StringBuffer error = new StringBuffer();
        if ("aliPay".equals(ordersPay.getTradeType()) || "aliPay-jsApi".equals(ordersPay.getTradeType())) {//支付宝
            thisProxy.doAliPayRefund(orders,ordersRefund,ordersInfo,returnGoods,refundDesc,register,ordersPay);
        } else if(PaySourceEnum.ADAPAY.getType().equals(ordersPay.getTradeType())){//汇付天下
            thisProxy.doAdapayRefund(orders, ordersRefund, ordersInfo, register, returnGoods);
        } else if ("UPAY".equals(ordersPay.getTradeType())){//首信易
            thisProxy.upayRefund(orders, ordersRefund, ordersInfo, register, returnGoods);
        } else if(PaySourceEnum.HFTX.getType().equals(ordersPay.getTradeType())){//汇付天下新
            thisProxy.hftxRefund(orders, ordersRefund, ordersInfo, register, returnGoods);
        } else if ("ZSY".equals(ordersPay.getTradeType())){
            thisProxy.ZsyRefund(orders, ordersRefund, ordersInfo, register, returnGoods);
        } else if("MHKJ".equals(ordersPay.getTradeType())){
            thisProxy.mhkjRefund(orders, ordersRefund, ordersInfo, register, returnGoods);
        } else {
            Map<String, String> response;
            log.info("==========TradeNo{}==========RefundNo={}",orders.getTradeNo(),ordersRefund.getRefundNo());
            if (PlatformConstant.PLATFORM_H5.equals(orders.getOrderSource()) || PlatformConstant.APP_PLATFORM.equals(orders.getOrderSource())
                    || PlatformConstant.H5_2_PLATFORM.equals(orders.getOrderSource()) || orders.getOrderSource().contains(PlatformConstant.PROVINCE_PLATFORM)
                    || PlatformConstant.H5_3_PLATFORM.equals(orders.getOrderSource())) {
                response = mallClient.h5RefundOrders(ordersPay.getTradeType(), orders.getTradeNo(), ordersRefund.getRefundNo(),
                        ordersRefund.getTotalFee(), ordersRefund.getRefundFee(), refundDesc);
            } else {
                response = mallClient.refundOrders(ordersPay.getTradeType(), orders.getTradeNo(), ordersRefund.getRefundNo(),
                        ordersRefund.getTotalFee(), ordersRefund.getRefundFee(), refundDesc);
            }
            if (response!=null){
                log.info("response,{}",JSON.toJSONString(response));
            }
            //如果上面调用出现错误（出错的原因：因为存在h5下单，app支付），所以这里再来做一次走APP的退款
            if ((null == response || null == response.get("return_code"))) {
                response = mallClient.refundOrders(ordersPay.getTradeType(), orders.getTradeNo(), ordersRefund.getRefundNo(),
                        ordersRefund.getTotalFee(), ordersRefund.getRefundFee(), refundDesc);
            }
            log.info("=================1111==============");
            String wxreidsFlag = redisService.get("wx_yebz_fs");
            //微信退款余额不足飞书预警
            if (!StringUtils.isEmpty(response.get("return_msg")) && (response.get("return_msg").contains(wxRefundText) || (!StringUtils.isEmpty(response.get("err_code_des")) && response.get("err_code_des").contains(wxRefundText))) && wxreidsFlag==null) {
                PayConfig payConfig = payConfigMapper.selectByPrimaryKey(ordersPay.getPayConfigId());
                FeiShuUtil.sendRefundMsg(PlatformEnum.getPlatformName(ordersInfo.getChildOrderNo().substring(0,1))
                        +"===微信商户号:"+payConfig.getMchId()+" 余额不足 请及时充值");
                log.info("===微信商户号:{} 余额不足 请及时充值,return_msg:{}",payConfig.getMchId(),response.get("return_msg"));
                redisService.set("wx_yebz_fs", "1", 60 * 60 * 1);
            }
            log.info("=================11112222==============");
            if (response == null) {
                ordersRefund.setStatus(3);
                refundMapper.updateByPrimaryKeySelective(ordersRefund);
                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.REFUND_FAILED) + ":" + response.get("return_msg"));
            }
            log.info("=================1111333==============");
            if ((!"SUCCESS".equals(response.get("return_code")) &&!"PROCESSING".equals(response.get("return_code"))) || "FAIL".equals(response.get("result_code"))) {
                ordersRefund.setStatus(3);
                ordersRefund.setResText(JSONObject.toJSONString(response));
                refundMapper.updateByPrimaryKeySelective(ordersRefund);
                log.info("==========response.get(\"return_msg\")=========={}",response.get("return_msg"));
                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.REFUND_FAILED) + ":" + response.get("return_msg"));
            }
            log.info("=================1111444==============");
            if(!PlatformConstant.PLATFORM_H5.equals(orders.getOrderSource()) && !PlatformConstant.APP_PLATFORM.equals(orders.getOrderSource())
                    && !PlatformConstant.H5_2_PLATFORM.equals(orders.getOrderSource())
                    && !orders.getOrderSource().contains(PlatformConstant.PROVINCE_PLATFORM)
                    && !PlatformConstant.H5_3_PLATFORM.equals(orders.getOrderSource())){
                if (!"SUCCESS".equals(response.get("result_code")) &&!"PROCESSING".equals(response.get("result_code")) || "FAIL".equals(response.get("result_code"))) {
                    ordersRefund.setStatus(3);
                    ordersRefund.setResText(JSONObject.toJSONString(response));
                    refundMapper.updateByPrimaryKeySelective(ordersRefund);
                    log.info("==========response.get(\"err_code_des\")=========={}",response.get("err_code_des"));
                    throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.REFUND_FAILED) + ":" + response.get("err_code_des"));
                }
            }

            log.info("=================222222==============");
            ordersRefund.setStatus(2);
            ordersRefund.setResText(JSONObject.toJSONString(response));
            refundMapper.updateByPrimaryKeySelective(ordersRefund);

            log.info("=================33333==============");

            // 同步退货管理中的退货状态
            ReturnGoods returnGoodsInfo = returnGoodsDao.getReturnGoodsByOid(register.getOrderInfoId());
            if (returnGoodsInfo != null) {
                returnGoodsDao.returnGoodsSuccess(returnGoodsInfo.getId());
            }
            String closeRemarks = getCloseRemarks(returnGoodsInfo);
            // 订单详情修改 退款单状态已完成的才更新订单状态
            String orderInfoStatus = ordersInfo.getOrderinfoStatus();
//            if (returnGoods.getStatus()==4){
//                orderInfoStatus ="4";
//            }
            ordersDao.updateStatusByOid(ordersInfo.getId(), "4",closeRemarks);

            // 原路返回页中订单详情状态改为已退款
            returnRegisterDao.modifiedReturnRegister(ordersInfo.getId());

            log.info("=================4444==============");

            // 订单修改 (只有所有详情中的订单状态为退款，主订单状态才改为退款)
            List<OrdersInfo> ordersInfoList = ordersDao.getAllOrdersInfoByOrderId(orders.getId());
            if (!CollectionUtils.isEmpty(ordersInfoList)) {
                int index = 0;
                for (OrdersInfo info : ordersInfoList) {
                    if (info.getOrderinfoStatus().equals("4")) {
                        index += 1;
                    }
                }
                if (index == ordersInfoList.size()) {
                    Orders order = new Orders();
                    order.setOrderStatus("4");
                    order.setIsRefund(1);
                    order.setRefundNo(ordersRefund.getRefundNo());
                    OrdersExample ordersExample = new OrdersExample();
                    ordersExample.createCriteria()
                            .andOrderNoEqualTo(ordersRefund.getOrderNo());
                    ordersMapper.updateByExampleSelective(order, ordersExample);

                    // 原路返回页中主订单状态改为已退款
                    returnRegisterDao.updateRegisterOrderStatus(ordersInfo.getId());
                }
            }

            log.info("===已退款，正在把库存加回来。。。。");
            if (null != returnGoods.getAfterType() && returnGoods.getAfterType() == 1){
                //售后类型为退款 把库存加回来
                try {
                    Product product = productMapper.selectByPrimaryKey(ordersInfo.getProductId());
                    subAndAddStock(ordersInfo.getChildOrderNo(),ordersInfo.getProductSum(),product.getIsZeroProduct(),"add");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            try {
//                addDeductionMoney(returnGoods,orders, ordersRefund);
            } catch (Exception e) {
                error.append("=========退款加抵扣金额失败=========");
                log.error("=========退款加抵扣金额失败========={}", e);
            }
            String s = addH5Score(ordersInfo, orders.getTel());
            if(!StringUtils.isEmpty(s)){
                error.append(s);
            }
            try {
                querySupplyChainOrderInfo(ordersInfo.getChildOrderNo(),returnGoods.getServiceNo());
            } catch (Exception e) {
                error.append("=========退款修改供应链订单失败=========");
                log.error("=========退款修改供应链订单失败========={}", e);
            }
        }

        //推送支付订单数据到阿里云
        new Thread(()->{
            try {
                AliyunMallRequest aliyunMallRequest = new AliyunMallRequest();
                aliyunMallRequest.setBatchName("");
                aliyunMallRequest.setChannelCode(orders.getChannel());
                aliyunMallRequest.setOrderTime(DateTimeUtil.TimeToStr(orders.getCreateTime()));
                aliyunMallRequest.setProvince(orders.getProvince());
                aliyunMallRequest.setStatus("3");
                aliyunMallRequest.setOrderNo(ordersInfo.getChildOrderNo());
                aliyunMallRequest.setPhone(orders.getTel());
                aliyunMallRequest.setPaymentAmount(orders.getRealTotalMoney().toString());
                BigDecimal refundMoney = new BigDecimal(ordersRefund.getRefundFee()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                aliyunMallRequest.setRefundAmount(refundMoney.toString());
                aliyunMallRequest.setName(orders.getUserName());
                aliyunMallRequest.setCost(ordersInfo.getCostPrice().toString());
                AliyunMallApiUtil.orderPush(aliyunMallRequest);
            } catch (Exception e) {
                log.error("退款订单推送阿里云失败", e);
            }
        }).start();

        //推送推呀事件信息
        try{
            EffectParamRequest effectParamRequest = new EffectParamRequest();
            effectParamRequest.setSubType(10);
            effectParamRequest.setH5Token(orders.getH5Token());
            effectParamRequest.setPaymentAmount(ordersRefund.getTotalFee().toString());
            mallClient.sendEffectData(effectParamRequest);
        }catch (Exception e) {
            log.error("推送到推呀事件信息错误:{}",e.getMessage());
        }

        //微信投诉单退款成功自动回复投诉单
        try{
            ComplaintsRecords records = complaintsService.queryByTradeNo(orders.getTradeNo());
            if (!ObjectUtils.isEmpty(records)) {
                BigDecimal refundMoney = new BigDecimal(ordersRefund.getTotalFee()).divide(new BigDecimal(100),2, RoundingMode.HALF_UP);
                String content = String.format(refundMessage, ordersInfo.getProductName(), refundMoney,"微信");
                String beginChildOrderNo = ordersInfo.getChildOrderNo().substring(0, 1);
                if ("NN".equals(beginChildOrderNo)) {
                    sendRefundMessage(records.getPayerPhone(),content,orders.getUserPhone(),guchuangRabbitTemplate);
                }
//                else if ("D".equals(beginChildOrderNo) ) {
//                    sendRefundMessage(records.getPayerPhone(),content,orders.getUserPhone(),jumaiduoRabbitTemplate);
//                } else if ("F".equals(beginChildOrderNo)) {
//                    sendRefundMessage(records.getPayerPhone(),content,orders.getUserPhone(),yiquanRabbitTemplate);
//                } else if("H".equals(beginChildOrderNo)) {
//                    sendRefundMessage(records.getPayerPhone(),content,orders.getUserPhone(),zxlpRabbitTemplate);
//                } else if ("O".equals(beginChildOrderNo)) {
//                    sendRefundMessage(records.getPayerPhone(),content,orders.getUserPhone(),ygyxRabbitTemplate);
//                } else if ("Q".equals(beginChildOrderNo)) {
//                    sendRefundMessage(records.getPayerPhone(),content,orders.getUserPhone(),yxhdRabbitTemplate);
//                } else if ("S".equals(beginChildOrderNo)) {
//                    sendRefundMessage(records.getPayerPhone(),content,orders.getUserPhone(),jckjRabbitTemplate);
//                }


            }
        }catch (Exception e) {
            log.error("微信投诉单退款成功发送短信失败：{}",e.getMessage());
        }


        if(error.length() > 0){
            return CommonResult.failed(error.toString());
        }else {
            return CommonResult.success();
        }
    }


    /**
     * 发送投诉单退款短信
     * @param complaintsUserPhone  投诉人手机号
     * @param content 短信内容
     * @param orderUserPhone 收件人手机号
     */
    private void sendRefundMessage(String complaintsUserPhone, String content, String orderUserPhone,RabbitTemplate rabbitTemplate) {

        if (org.apache.commons.lang3.StringUtils.isNotBlank(complaintsUserPhone)) {
            SmsDto dto = new SmsDto();
            dto.setType(11);
            dto.setPhone(complaintsUserPhone);
            dto.setCode(content);
            rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
            if (!complaintsUserPhone.equals(orderUserPhone)) {
                SmsDto dto2 = new SmsDto();
                dto2.setType(11);
                dto2.setPhone(orderUserPhone);
                dto2.setCode(content);
                rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
            }
        } else {
            SmsDto dto = new SmsDto();
            dto.setType(11);
            dto.setPhone(orderUserPhone);
            dto.setCode(content);
            rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
        }
    }
    /**
     * 加积分
     */
    public String addH5Score(OrdersInfo ordersInfo, String tel){
        StringBuffer error = new StringBuffer();
        //退积分（加回积分）
        if("CASH_SCORE".equals(ordersInfo.getActivityType())){
            log.info("===已退款，正在把【积分】加回来。。。。===ordersInfo:{}=== tel:{}",JSON.toJSONString(ordersInfo),tel);
            try {
                usersClient.h5AddScore(ordersInfo.getActivityMax().intValue(),tel);
            } catch (Exception e) {
                error.append("=========退款加积分失败=========");
                log.error("=========退款加积分失败========={}", e);
            }
        }
        return error.toString();
    }

    @Override
    public void doAliPayRefund(Orders orders,OrdersRefund ordersRefund,OrdersInfo ordersInfo,ReturnGoods returnGoods,String refundDesc,ReturnRegister register,OrdersPay ordersPay){
        try {
            StringBuffer msg = new StringBuffer();
            AlipayTradeRefundResponse response = null;
            // 退款表状态更新
            ordersRefund.setStatus(2);
            ordersRefund.setResText(JSONObject.toJSONString(response));
            refundMapper.updateByPrimaryKeySelective(ordersRefund);

            //优先从数据库配置找到对应的退款 历史没有pay_config_id的还是之前的逻辑
            if (ordersPay.getPayConfigId()!=null){
                try {
                    YxAlipayConfig alipayConfig = ordersPayMapper.findAliPayById(ordersPay.getPayConfigId());
                    response = alipayService.refundAliPayOrderMysql(orders.getTradeNo(), ordersRefund.getRefundNo(),
                             ordersRefund.getRefundFee(), refundDesc,alipayConfig);
                    msg.append(alipayConfig.getCompany()+alipayConfig.getAccount()+":"+response.getSubMsg()+"===");
                } catch (Exception e) {
                    log.error("调用支付宝接口出错,{}",e);
                    FeiShuUtil.sendMsg(String.format("调用支付宝接口出错,%s",e.getMessage()));
                    throw new ApiException(String.format("调用支付宝接口出错,%s",e.getMessage()));
                }
            } else {
                //从第1商户退款
                try {
                    if ("aliPay-jsApi".equals(ordersPay.getTradeType())) {
                        response = alipayService.refundJsaApiAliPayOrder(ordersPay.getTransactionId(), ordersRefund.getRefundNo(),
                                ordersRefund.getTotalFee(), ordersRefund.getRefundFee(), refundDesc,ordersPay.getChildId());
                    } else {
                        response = alipayService.refundAliPayOrderOld(orders.getTradeNo(), ordersRefund.getRefundNo(),
                                ordersRefund.getTotalFee(), ordersRefund.getRefundFee(), refundDesc,ordersPay.getChildId());
                    }
                    msg.append("XXXX优品02:"+response.getSubMsg()+"===");
                    log.info("支付宝退款返回信息01:{},{},{},{}",response.getMsg(),response.getCode(),response.getSubMsg(),ordersPay.getChildId());
                } catch (AlipayApiException e) {
                    log.error("调用支付宝接口出错,{}",e);
                    FeiShuUtil.sendMsg(String.format("调用支付宝接口出错,%s",e.getMessage()));
                    throw new ApiException(String.format("调用支付宝接口出错,%s",e.getMessage()));
                }

                //退款失败，再从第3个商户退款
                if(!"aliPay-jsApi".equals(ordersPay.getTradeType()) && !response.getMsg().equals("Success") || !response.getCode().equals("10000")){
                    try {
                        response = alipayService.refundAliPayOrder05(orders.getTradeNo(), ordersRefund.getRefundNo(),
                                ordersRefund.getTotalFee(), ordersRefund.getRefundFee(), refundDesc);
                        msg.append("XXXX优品05:"+response.getSubMsg()+"===");
                        log.info("支付宝退款返回信息05:{},{},{},{}",response.getMsg(),response.getCode(),response.getSubMsg(),ordersPay.getChildId());
                    } catch (AlipayApiException e) {
                        log.error("调用支付宝接口出错,{}",e);
                        FeiShuUtil.sendMsg(String.format("调用支付宝接口出错,%s",e.getMessage()));
                        throw new ApiException(String.format("调用支付宝接口出错,%s",e.getMessage()));
                    }
                }
            }

            if (!response.getMsg().equals("Success") || !response.getCode().equals("10000")) {
                String resText = ordersPay.getResText();
                Map<String, String> map = JSONObject.parseObject(resText, Map.class);
                String seller_email = map.get("seller_email");
                String zfbreidsFlag = redisService.get("zfb_yebz_fs_"+seller_email);
                //支付宝退款余额不足飞书预警
                if (msg.toString().contains(aliPayRefundText) && zfbreidsFlag==null) {
                    //查询已标记的待退款总金额
                    String autoAmount = returnGoodsDao.getReturnAutoAmount(seller_email);
                    if (autoAmount ==null){
                        autoAmount = "0";
                    }

                    FeiShuUtil.sendRefundMsg(PlatformEnum.getPlatformName(ordersInfo.getChildOrderNo().substring(0,1))
                            +"===支付宝账号:"+map.get("seller_email")+" 余额不足 请及时充值,已标记待退款金额:"+autoAmount);
                    redisService.set("zfb_yebz_fs_"+seller_email, "1", 60 * 60 * 1);
                }
                throw new ApiException(String.format("退款失败,%s", msg.toString()));
            }

            //支付宝投诉单退款成功自动回复投诉单
            try{
                AlipayComplaintsRecords records = aliPayComplaintsService.queryByTradeNo(orders.getTradeNo());
                if (!ObjectUtils.isEmpty(records)) {
                    BigDecimal refundMoney = new BigDecimal(ordersRefund.getTotalFee()).divide(new BigDecimal(100),2, RoundingMode.HALF_UP);
                    String content = String.format(refundMessage, ordersInfo.getProductName(), refundMoney,"支付宝");
                    String beginChildOrderNo = ordersInfo.getChildOrderNo().substring(0, 1);
                    if ("NN".equals(beginChildOrderNo)) {
                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),guchuangRabbitTemplate);
                    }
//                    else if ("D".equals(beginChildOrderNo) ) {
//                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),jumaiduoRabbitTemplate);
//                    } else if ("F".equals(beginChildOrderNo)) {
//                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),yiquanRabbitTemplate);
//                    } else if("H".equals(beginChildOrderNo)) {
//                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),zxlpRabbitTemplate);
//                    } else if ("O".equals(beginChildOrderNo)) {
//                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),ygyxRabbitTemplate);
//                    } else if ("Q".equals(beginChildOrderNo)) {
//                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),yxhdRabbitTemplate);
//                    } else if ("S".equals(beginChildOrderNo)) {
//                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),jckjRabbitTemplate);
//                    }

                }
            }catch (Exception e) {
                log.error("支付宝投诉单退款成功发送短信失败：{}",e.getMessage());
            }


            if (!response.getMsg().equals("Success") || !response.getCode().equals("10000")) {
                ordersRefund.setStatus(3);
                ordersRefund.setResText(JSONObject.toJSONString(response));
                refundMapper.updateByPrimaryKeySelective(ordersRefund);
                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.REFUND_FAILED) + ":" + response.getSubMsg());
            } else {
                thisProxy.updateAdminOrderInfo(orders,ordersRefund,ordersInfo,register,returnGoods);
                //更新供应链订单状态 * 销售端调用 （当销售端退款后，需要修改订单状态）
                querySupplyChainOrderInfo(ordersInfo.getChildOrderNo(),returnGoods.getServiceNo());
            }
        } catch (ApiException e) {
            throw e;
        }
    }

    /**
     * 执行汇付天下的退款
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doAdapayRefund(Orders orders,OrdersRefund ordersRefund,OrdersInfo ordersInfo,ReturnRegister register,ReturnGoods returnGoods){
        String orderNo = orders.getOrderNo();
        OrdersPay ordersPayByOrderNo = ordersPayMapper.findOrdersPayByOrderNo(orderNo);
        if (null == ordersPayByOrderNo) {
            throw new ApiException("订单不存在！");
        }
        String resText = ordersPayByOrderNo.getResText();
        Map<String, Object> payRes = JSON.parseObject(resText, Map.class);
        Object paymentId = payRes.get("id");
        //查询当前退款状态
        try {
            Map<String, Object> stringObjectMap = adaPayService.queryRefund(paymentId.toString(), null, null);
            List<Map> refunds = JSON.parseArray(JSON.toJSONString(stringObjectMap.get("refunds")), Map.class);
            if(!CollectionUtils.isEmpty(refunds)){
                for (Map refund : refunds) {
                    String transStatus =(String) refund.get("trans_status");
                    if("S".equals(transStatus)){
                        // 退款成功，退款表状态更新
                        ordersRefund.setStatus(2);
                        ordersRefund.setResText(JSONObject.toJSONString(refund));
                        refundMapper.updateByPrimaryKeySelective(ordersRefund);
                        //更新供应链订单状态,销售端调用 （当销售端退款后，需要修改订单状态）
                        querySupplyChainOrderInfo(ordersInfo.getChildOrderNo(), returnGoods.getServiceNo());
                        return;
                    }
                }
            }
        } catch (Exception e) {
            log.error("调用adapay查询退款信息出错,{}",e);
        }

        thisProxy.updateAdminOrderInfo(orders,ordersRefund,ordersInfo,register,returnGoods);
        //退款响应结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap = adaPayService.executeRefund(paymentId.toString(), ordersRefund.getRefundFee().toString(), ordersPayByOrderNo.getResOrderNo());
        if (null == resultMap && ("failed".equals(resultMap.get("status")) && !"order_no_used".equals(resultMap.get("error_code")))) {
            String error = String.format("退款失败:%s。错误码:%s", resultMap.get("error_msg"), resultMap.get("error_code"));
            log.error(error);
            throw new ApiException(error);
        }
        //退款中
        if(null != resultMap && "pending".equals(resultMap.get("status"))){
            throw new ApiException("退款已发起，请刷新页面查看最新状态...");
        }
        //成功
        else if (null != resultMap && "succeeded".equals(resultMap.get("status"))) {
            // 退款成功，退款表状态更新
            ordersRefund.setStatus(2);
            ordersRefund.setResText(JSONObject.toJSONString(resultMap));
            refundMapper.updateByPrimaryKeySelective(ordersRefund);
            //更新供应链订单状态,销售端调用 （当销售端退款后，需要修改订单状态）
            querySupplyChainOrderInfo(ordersInfo.getChildOrderNo(), returnGoods.getServiceNo());
        }else {
            throw new ApiException(JSON.toJSONString("退款失败！"+resultMap));
        }
    }

    @Override
    public void upayRefund(Orders orders, OrdersRefund ordersRefund, OrdersInfo ordersInfo, ReturnRegister register, ReturnGoods returnGoods) {
        OrdersPay ordersPay =ordersPayMapper.queryByOrderNo(orders.getOrderNo());
        if (ordersPay!=null){
            int flag =mallClient.upayRefund(ordersPay.getTransactionId(),String.valueOf(ordersRefund.getId()),String.valueOf(ordersRefund.getRefundFee()));
            if (flag==0){
                // 退款表状态更新
                ordersRefund.setStatus(3);
                refundMapper.updateByPrimaryKeySelective(ordersRefund);

                FeiShuUtil.sendMsg("调用首信易支付退款失败,请检查");
                throw new ApiException(String.format("调用首信易支付退款失败,请联系管理员"));
            }
        }
    }

    @Override
    public void hftxRefund(Orders orders, OrdersRefund ordersRefund, OrdersInfo ordersInfo, ReturnRegister register, ReturnGoods returnGoods) {
        try {
            OrdersPay ordersPay =ordersPayMapper.queryByOrderNo(orders.getOrderNo());
            if (ordersPay!=null && ordersPay.getTransactionId()!=null){
                Map<String, Object> refundParams = new HashMap<String, Object>();
                refundParams.put("refund_amt", returnGoods.getAmount().toString());
                refundParams.put("refund_order_no", String.valueOf(ordersRefund.getId()));
                refundParams.put("notify_url", REFUND_NOTIFY_URL);
                Map<String, Object> response = Refund.create(ordersPay.getTransactionId(), refundParams);
                log.info("汇付天下Refund.create返回数据,{}",JSON.toJSONString(response));
                if ("failed".equals(response.get("status"))){
                    throw new ApiException(response.get("error_msg").toString());
                }
            }
        } catch (Exception e) {
//            FeiShuUtil.sendMsg("调用汇付天下退款失败,"+e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @Override
    public void ZsyRefund(Orders orders,OrdersRefund ordersRefund,OrdersInfo ordersInfo,ReturnRegister register,ReturnGoods returnGoods){
        int flag =mallClient.zsyRefund(orders.getTradeNo(),ordersRefund.getRefundNo(),String.valueOf(ordersRefund.getRefundFee()), DateTimeUtil.TimeToStr(orders.getPayTime()));
        if (flag==0){
            // 退款表状态更新
            ordersRefund.setStatus(3);
            refundMapper.updateByPrimaryKeySelective(ordersRefund);

//            FeiShuUtil.sendMsg("调用首信易支付退款失败,请检查");
            throw new ApiException(String.format("调用智收营退款失败,请联系管理员"));
        }else {
            //支付宝投诉单退款成功自动回复投诉单
            try{
                AlipayComplaintsRecords records = aliPayComplaintsService.queryByTradeNo(orders.getTradeNo());
                if (!ObjectUtils.isEmpty(records)) {
                    BigDecimal refundMoney = new BigDecimal(ordersRefund.getTotalFee()).divide(new BigDecimal(100),2, RoundingMode.HALF_UP);
                    String content = String.format(refundMessage, ordersInfo.getProductName(), refundMoney,"支付宝");
                    String beginChildOrderNo = ordersInfo.getChildOrderNo().substring(0, 1);
                    if ("NN".equals(beginChildOrderNo)) {
                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),guchuangRabbitTemplate);
                    }
//                    else if ("D".equals(beginChildOrderNo) ) {
//                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),jumaiduoRabbitTemplate);
//                    } else if ("F".equals(beginChildOrderNo)) {
//                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),yiquanRabbitTemplate);
//                    } else if("H".equals(beginChildOrderNo)) {
//                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),zxlpRabbitTemplate);
//                    } else if ("O".equals(beginChildOrderNo)) {
//                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),ygyxRabbitTemplate);
//                    } else if ("Q".equals(beginChildOrderNo)) {
//                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),yxhdRabbitTemplate);
//                    } else if ("S".equals(beginChildOrderNo)) {
//                        sendRefundMessage(records.getPhoneNo(),content,orders.getUserPhone(),jckjRabbitTemplate);
//                    }

                }
            }catch (Exception e) {
                log.error("支付宝投诉单退款成功发送短信失败：{}",e.getMessage());
            }
        }

    }

    @Override
    public void mhkjRefund(Orders orders,OrdersRefund ordersRefund,OrdersInfo ordersInfo,ReturnRegister register,ReturnGoods returnGoods){
        String result = mallClient.mhkjRefund(orders.getTradeNo(),ordersRefund.getRefundNo(),String.valueOf(ordersRefund.getRefundFee()), DateTimeUtil.TimeToStr(orders.getPayTime()));
        if (!"成功".equals(result)){
            // 退款表状态更新
            ordersRefund.setStatus(3);
            refundMapper.updateByPrimaryKeySelective(ordersRefund);

//            FeiShuUtil.sendMsg("调用首信易支付退款失败,请检查");
            throw new ApiException(String.format("调用米花支付退款失败,%s",result));
        }

    }

    @Override
    public void updateAdminOrderInfo(Orders orders, OrdersRefund ordersRefund, OrdersInfo ordersInfo, ReturnRegister register, ReturnGoods returnGoods) {
        // 同步退货管理中的退货状态
        ReturnGoods returnGoodsInfo = returnGoodsDao.getReturnGoodsByOid(register.getOrderInfoId());
        if (returnGoodsInfo != null) {
            returnGoodsDao.returnGoodsSuccess(returnGoodsInfo.getId());
        }
        //交易关闭原因
        String closeRemarks = getCloseRemarks(returnGoodsInfo);
        // 订单详情修改 退款单状态已完成的才更新订单状态
//        String orderInfoStatus = ordersInfo.getOrderinfoStatus();
//        if (returnGoods.getStatus() == 4) {
//            orderInfoStatus = "4";
//        }
        //退款成功改为已关闭
        ordersDao.updateStatusByOid(ordersInfo.getId(), "4", closeRemarks);
        // 原路返回页中订单详情状态改为已退款
        returnRegisterDao.modifiedReturnRegister(ordersInfo.getId());

        // 订单修改 (只有所有详情中的订单状态为退款，主订单状态才改为退款)
        List<OrdersInfo> ordersInfoList = ordersDao.getAllOrdersInfoByOrderId(orders.getId());
        if (!CollectionUtils.isEmpty(ordersInfoList)) {
            int index = 0;
            for (OrdersInfo info : ordersInfoList) {
                if (info.getOrderinfoStatus().equals("4")) {
                    index += 1;
                }
            }
            if (index == ordersInfoList.size()) {
                Orders order = new Orders();
                order.setOrderStatus("4");//------------------------退款成功改为已关闭
                order.setIsRefund(1);
                order.setRefundNo(ordersRefund.getRefundNo());
                OrdersExample ordersExample = new OrdersExample();
                ordersExample.createCriteria()
                        .andOrderNoEqualTo(ordersRefund.getOrderNo());
                ordersMapper.updateByExampleSelective(order, ordersExample);
                // 原路返回页中主订单状态改为已退款
                returnRegisterDao.updateRegisterOrderStatus(ordersInfo.getId());
            }
        }
        if (null != returnGoods.getAfterType() && returnGoods.getAfterType() == 1) {
            //售后类型为退款 把库存加回来
            Product product = productMapper.selectByPrimaryKey(ordersInfo.getProductId());
            subAndAddStock(ordersInfo.getChildOrderNo(), ordersInfo.getProductSum(), product.getIsZeroProduct(), "add");
        }
        //退抵扣金额
        //退款金额分几个情况处理
//        addDeductionMoney(returnGoods, orders, ordersRefund);
    }

    /**
     * //如果没有支付信息(纯余额支付),退回用户余额
     * @param register
     * @param ordersInfo
     * @param orders
     * @param returnGoods
     * @param ordersRefund
     */
    public void returnBalance(ReturnRegister register, OrdersInfo ordersInfo, Orders orders, ReturnGoods returnGoods, OrdersRefund ordersRefund) {
        UsersBalanceRecordRequest usersBalanceRecordRequest = new UsersBalanceRecordRequest();
        usersBalanceRecordRequest.setBalance(returnGoods.getAmount());
        usersBalanceRecordRequest.setSource("REFUND");
        usersBalanceRecordRequest.setType("ADD");
        usersBalanceRecordRequest.setUserId(orders.getUserId());
        usersBalanceRecordService.insertRecord(usersBalanceRecordRequest);
        // 退款表状态更新
        ordersRefund.setStatus(2);
        ordersRefund.setResText("纯余额退款成功");
        refundMapper.updateByPrimaryKeySelective(ordersRefund);

        // 原路返回页中订单详情状态改为已退款
        returnRegisterDao.modifiedReturnRegister(ordersInfo.getId());

        // 同步退货管理中的退货状态
        ReturnGoods returnGoodsInfo = returnGoodsDao.getReturnGoodsByOid(register.getOrderInfoId());
        if(returnGoodsInfo != null) {
            returnGoodsDao.returnGoodsSuccess(returnGoodsInfo.getId());
        }
        String closeRemarks = getCloseRemarks(returnGoodsInfo);
        // 订单详情修改
        ordersDao.updateStatusByOid(ordersInfo.getId(), "4", closeRemarks);//------------------------退款成功改为已关闭

        // 订单修改 (只有所有详情中的订单状态为退款，主订单状态才改为退款)
        updateOrderStatus(ordersInfo, orders, ordersRefund, closeRemarks);

        try {
            querySupplyChainOrderInfo(ordersInfo.getChildOrderNo(),returnGoods.getServiceNo());
        } catch (Exception e) {
            log.error("=========退款修改供应链订单失败========={}", e);
        }
    }

    /**
     * 修改主订单状态
     * @param ordersInfo
     * @param orders
     * @param ordersRefund
     * @param closeRemarks
     */
    public void updateOrderStatus(OrdersInfo ordersInfo, Orders orders, OrdersRefund ordersRefund, String closeRemarks) {
        List<OrdersInfo> ordersInfoList = ordersDao.getAllOrdersInfoByOrderId(orders.getId());
        if (!CollectionUtils.isEmpty(ordersInfoList)) {
            int index = 0;
            for (OrdersInfo info : ordersInfoList) {
                if (info.getOrderinfoStatus().equals("4")) {
                    index += 1;
                }
            }
            if (index == ordersInfoList.size()) {
                Orders order = new Orders();
                order.setOrderStatus("4");//------------------------退款成功改为已关闭
                order.setOrderRemarks(closeRemarks);
                order.setIsRefund(1);
                order.setRefundNo(ordersRefund.getRefundNo());
                OrdersExample ordersExample = new OrdersExample();
                ordersExample.createCriteria()
                        .andOrderNoEqualTo(ordersRefund.getOrderNo());
                ordersMapper.updateByExampleSelective(order, ordersExample);

                // 原路返回页中主订单状态改为已退款
                returnRegisterDao.updateRegisterOrderStatus(ordersInfo.getId());
            }
        }
    }

    /**
     * 获取交易关闭原因
     * @param returnGoodsInfo
     * @return
     */
    public String getCloseRemarks(ReturnGoods returnGoodsInfo) {
        String closeRemarks = "";
        if (returnGoodsInfo.getAfterType() == 1) {
            closeRemarks = "订单已申请退款";
        } else if (returnGoodsInfo.getAfterType() == 2) {
            closeRemarks = "订单已申请退货退款";
        } else if (returnGoodsInfo.getAfterType() == 3) {
            closeRemarks = "订单已申请仅退款";
        }
        return closeRemarks;
    }

    /**
     * 抵扣金额退款
     * @param orders
     * @param ordersRefund
     */
    public void addDeductionMoney(ReturnGoods returnGoods, Orders orders, OrdersRefund ordersRefund) {
//        int amount = returnGoods.getAmount().multiply(new BigDecimal(100)).intValue();
//        //退抵扣金额
//        if (null != orders.getDeductionMoney() && orders.getDeductionMoney().compareTo(new BigDecimal(0)) > 0){
//            //退款金额分几个情况处理
//            OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
//            ordersInfoExample.createCriteria().andOrderIdEqualTo(orders.getId());
//            List<OrdersInfo> ordersInfos = ordersInfoMapper.selectByExample(ordersInfoExample);
//            if (ordersInfos.size() > 0 && ordersInfos.size() < 2) {
//                UsersBalanceRecordRequest usersBalanceRecordRequest = new UsersBalanceRecordRequest();
//                usersBalanceRecordRequest.setBalance(returnGoods.getAmount().subtract(orders.getRealTotalMoney()));
//                usersBalanceRecordRequest.setSource("REFUND");
//                usersBalanceRecordRequest.setType("ADD");
//                usersBalanceRecordRequest.setUserId(orders.getUserId());
//                usersBalanceRecordService.insertRecord(usersBalanceRecordRequest);
//            } else {
//                if (null == orders.getRealTotalMoneyRefund()) {
//                    int realTotalMoney = orders.getRealTotalMoney().multiply(new BigDecimal(100)).intValue();
//
//                    if (amount > realTotalMoney) {
//                        UsersBalanceRecordRequest usersBalanceRecordRequest = new UsersBalanceRecordRequest();
//                        BigDecimal realTotalMoneyRefund = new BigDecimal(amount - realTotalMoney).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_CEILING);
//                        usersBalanceRecordRequest.setBalance(realTotalMoneyRefund);
//                        usersBalanceRecordRequest.setSource("REFUND");
//                        usersBalanceRecordRequest.setType("ADD");
//                        usersBalanceRecordRequest.setUserId(orders.getUserId());
//                        usersBalanceRecordService.insertRecord(usersBalanceRecordRequest);
//                        orders.setRealTotalMoneyRefund(new BigDecimal(0));
//                        orders.setDeductionMoneyRefund(orders.getDeductionMoney().subtract(orders.getRealTotalMoney()));
//                        ordersMapper.updateByPrimaryKeySelective(orders);
//                    } else {
//                        orders.setRealTotalMoneyRefund(new BigDecimal(realTotalMoney - ordersRefund.getRefundFee()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_CEILING));
//                        orders.setDeductionMoneyRefund(orders.getDeductionMoney());
//                        ordersMapper.updateByPrimaryKeySelective(orders);
//                    }
//
//                } else {
//                    int realTotalMoneyRefund = orders.getRealTotalMoneyRefund().multiply(new BigDecimal(100)).intValue();
//                    if (amount > realTotalMoneyRefund) {
//                        BigDecimal money = new BigDecimal(amount - realTotalMoneyRefund).divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
//                        UsersBalanceRecordRequest usersBalanceRecordRequest = new UsersBalanceRecordRequest();
//                        usersBalanceRecordRequest.setBalance(money);
//                        usersBalanceRecordRequest.setSource("REFUND");
//                        usersBalanceRecordRequest.setType("ADD");
//                        usersBalanceRecordRequest.setUserId(orders.getUserId());
//                        usersBalanceRecordService.insertRecord(usersBalanceRecordRequest);
//                        orders.setRealTotalMoneyRefund(new BigDecimal(0));
//                        orders.setDeductionMoneyRefund(orders.getDeductionMoney().subtract(money));
//                        ordersMapper.updateByPrimaryKeySelective(orders);
//                    } else {
//                        orders.setRealTotalMoneyRefund(orders.getRealTotalMoneyRefund().subtract(new BigDecimal(ordersRefund.getRefundFee()).divide(new BigDecimal(100).setScale(2, BigDecimal.ROUND_CEILING))));
//                        orders.setDeductionMoneyRefund(orders.getDeductionMoney());
//                        ordersMapper.updateByPrimaryKeySelective(orders);
//                    }
//                }
//            }
//        }

    }

    @Override
    public Integer selectByOrderInfoId(Integer orderInfoId) {
        return returnRegisterDao.queryCountReturnRegisterByOrderInfoId(orderInfoId);
    }

    /**
     *  更新供应链订单状态
     *      * 销售端调用 （当销售端退款后，需要修改订单状态）
     */
    @Override
    public void querySupplyChainOrderInfo(String childOrderNo,String serviceNo) {
        UpdateOrderStatusRequest updateOrderStatusRequest = new UpdateOrderStatusRequest();
        updateOrderStatusRequest.setChildOrderNo(childOrderNo);
        updateOrderStatusRequest.setShopId(supplyApiConfig.getShopId());
        updateOrderStatusRequest.setOrderStatus(4);
        String json = JSON.toJSONString(updateOrderStatusRequest);
        HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/updateOrderStatus", json, supplyApiConfig.getHeadsMap());

        YxReturnGoods yxReturnGoodsRequest = new YxReturnGoods();
        yxReturnGoodsRequest.setServiceNo(serviceNo);
        yxReturnGoodsRequest.setStatus(9);
        updateReturnGoods(yxReturnGoodsRequest);
    }
    /**
     * 更新供应链售后信息
     */
    public void updateReturnGoods(YxReturnGoods request){
        request.setShopId(supplyApiConfig.getShopId());
        String json = JSON.toJSONString(request);
        HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/updateReturnGoods", json, supplyApiConfig.getHeadsMap());
    }

    /**
     * 扣减或退还库存
     * @param num 商品数量
     * @param type sub-扣减 add-退还
     * @return
     */public void subAndAddStock( String orderNo, Integer num,Integer isZeroProduct, String type) {
        Map<String,String> map = new LinkedMap();
        map.put("orderNo", orderNo);
        map.put("num", String.valueOf(num));
        map.put("isZeroProduct", String.valueOf(isZeroProduct));
        map.put("type", type);
        HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/stock/subAndAddStock", map, supplyApiConfig.getHeadsMap());
    }

    /**
     * 退货管理中修改责任人时，更新原路返回表中的字段
     * @auth jiangkang
     * @param ordersInfoId=订单详情id
     * @param orderType=订单类型
     * @param reasonType=原因类型
     * @param reasonDetail=具体原因
     */
    @Override
    public void updateByEditReturnGoods(Integer ordersInfoId, Integer orderType, Integer reasonType, String reasonDetail) {
         if (null == ordersInfoId) {
             return;
         }
         ReturnRegisterExample example = new ReturnRegisterExample();
         example.createCriteria().andOrderInfoIdEqualTo(ordersInfoId).andStatusEqualTo(0);
         example.setOrderByClause("id desc");
         List<ReturnRegister> list = returnRegisterMapper.selectByExample(example);
         if (CollectionUtils.isEmpty(list)) {
             return;
         }
         ReturnRegister returnRegister = list.get(0);
         returnRegister.setOrderType(orderType);
         returnRegister.setReasonType(reasonType);
         returnRegister.setSpecificReason(reasonDetail);
         returnRegisterMapper.updateByPrimaryKeySelective(returnRegister);
    }
}
